package com.exsun.ex1077.ui.popup

import android.content.Context
import android.graphics.Color
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.view.TimePickerView
import com.drake.brv.utils.linear
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.exsun.ex1077.R
import com.zhangping.fastjetpack.model.Tree
import com.google.android.flexbox.FlexboxLayoutManager
import com.lxj.xpopup.impl.PartShadowPopupView
import com.zhangping.fastjetpack.binding.visible
import com.zhangping.fastjetpack.callback.CommonCallback
import com.zhangping.fastjetpack.extend.*
import com.zhangping.fastjetpack.extend.view.textString
import com.zhangping.fastjetpack.model.Item
import kotlinx.android.synthetic.main.activity_search.*
import kotlinx.android.synthetic.main.popuo_list_menu.view.*
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashSet

/**
 * 描述：车辆列表/里程列表筛选菜单
 * 作者：ZhangPing
 * 创建时间：2023/3/22 14:48
 */
class ListMenuPopup(context: Context, val mileageCountModel: Boolean = false) : PartShadowPopupView(context){

    override fun getImplLayoutId() = R.layout.popuo_list_menu

    private var companyTreeData: List<Tree>? = null
    private var manageTypeData: List<Item>? = null
    private lateinit var startTimePicker: TimePickerView
    private lateinit var endTimePicker: TimePickerView
    private lateinit var tabLayouts: List<FrameLayout>
    private lateinit var tabBars: List<View>
    private lateinit var tabTexts: List<TextView>
    private val initStartDate: Date by lazy { Calendar.getInstance().apply { add(Calendar.DAY_OF_MONTH, -3) }.time }
    private val initEndDate: Date by lazy { Calendar.getInstance().apply { add(Calendar.DAY_OF_MONTH, -1) }.time }
    private var onConfirmListener: CommonCallback? = null

    override fun onCreate() {
        //初始化公司树
        companyListView.linear().setup {
            addType<Tree>(R.layout.list_item_area)
            onClick(R.id.checkBox, R.id.itemRoot){
                if (it == R.id.itemRoot){
                    expandOrCollapse()
                    return@onClick
                }
                //更新选中状态
                val model = getModel<Tree>(modelPosition)
                updateCheckBoxState(model, model.checked)
                postDelayed({ notifyDataSetChanged() }, 100)
            }
        }.models = companyTreeData
        //初始化监管类型树
        typeListView.layoutManager = FlexboxLayoutManager(activity)
        typeListView.setup {
            addType<Item>(R.layout.item_list_menu_type)
            onClick(R.id.rootView){
                val model = getModel<Item>()
                model.checked = !model.checked
                notifyItemChanged(modelPosition)
            }
        }.models = manageTypeData
        typeSelectAll.setOnClickListener {
            typeListView.models?.let {
                val itemList = it as List<Item>
                if (itemList.count { it.checked } == it.size){
                    itemList.forEach { it.checked = false }
                }else{
                    itemList.forEach { it.checked = true }
                }
                typeListView.adapter?.notifyDataSetChanged()
            }
        }
        tabLayouts = arrayListOf(selectCompany, selectObject, selectTime)
        tabBars = arrayListOf(companyBar, objectBar, timeBar)
        tabTexts = arrayListOf(companyText, objectText, timeText)
        startTimePicker = TimePickerBuilder(activity){date, v ->
            startTime.text = date.toDateStr()
        }.build()
        endTimePicker = TimePickerBuilder(activity){date, v ->
            endTime.text = date.toDateStr()
        }.build()
        if (mileageCountModel){
            //初始化默认设置时间
            startTime.text = initStartDate.toDateStr()
            startTimePicker.setDate(Calendar.getInstance().apply { time = initStartDate })
            endTime.text = initEndDate.toDateStr()
            endTimePicker.setDate(Calendar.getInstance().apply { time = initEndDate })
        }
        startTime.setOnClickListener {
            startTime.setTextColor(R.color.theme.toColorRes())
            startTime.setBackgroundResource(R.drawable.shape_radius5_bd_theme_bg_e4edff)
            endTime.setTextColor(R.color.color_666666.toColorRes())
            endTime.setBackgroundResource(R.drawable.shape_radius5_bg_f9f9ff)
            startTimePicker.show()
        }
        endTime.setOnClickListener {
            startTime.setTextColor(R.color.color_666666.toColorRes())
            startTime.setBackgroundResource(R.drawable.shape_radius5_bg_f9f9ff)
            endTime.setTextColor(R.color.theme.toColorRes())
            endTime.setBackgroundResource(R.drawable.shape_radius5_bd_theme_bg_e4edff)
            endTimePicker.show()
        }
        selectCompany.setOnClickListener {
            changeTabStatus(0)
            scrollView.smoothScrollTo(0, 0)
        }
        selectObject.setOnClickListener {
            changeTabStatus(1)
            scrollView.smoothScrollTo(0, objectTitleLayout.top)
        }
        selectTime.setOnClickListener {
            changeTabStatus(2)
            scrollView.smoothScrollTo(0, timeTitleView.top)
        }
        reset.setOnClickListener {
            companyListView.models?.let {
                it.forEach {
                    updateCheckBoxState(it as Tree, false)
                }
                postDelayed({ companyListView.adapter?.notifyDataSetChanged() },100)
            }
            changeTabStatus(0)
            typeListView.models?.let {
                (it as List<Item>).forEach { it.checked = false }
                typeListView.adapter?.notifyDataSetChanged()
            }
            startTime.apply {
                setTextColor(R.color.color_666666.toColorRes())
                setBackgroundResource(R.drawable.shape_radius5_bg_f9f9ff)
                if (mileageCountModel){
                    text = initStartDate.toDateStr()
                    startTimePicker.setDate(Calendar.getInstance().apply { time = initStartDate })
                }else{
                    text = ""
                }
            }
            endTime.apply {
                setTextColor(R.color.color_666666.toColorRes())
                setBackgroundResource(R.drawable.shape_radius5_bg_f9f9ff)
                if (mileageCountModel){
                    text = initEndDate.toDateStr()
                    endTimePicker.setDate(Calendar.getInstance().apply { time = initEndDate })
                }else{
                    text = ""
                }
            }
        }
        result.setOnClickListener {
            if (startTime.textString().isNotEmpty()
                && endTime.textString().isNotEmpty()
                && startTime.textString().afterDate(endTime.textString(), "yyyy-MM-dd")){
                "结束时间不能小于开始时间".showToast()
                return@setOnClickListener
            }
            dismiss()
            onConfirmListener?.onCall()
        }
    }

    /**
     * 获取选中的部门ID
     */
    fun getDeptIdList(): List<String> {
        val list = companyListView?.models ?: return emptyList()
        val selectedMenus = list.filter { (it as Tree).checked } as List<Tree>
        val resultList = HashSet<String>()
        extractChildMenuId(selectedMenus, resultList)
        return ArrayList(resultList)
    }

    /**
     * 获取选中的监管类型
     */
    fun getManageTypeList(): List<String> {
        val list = typeListView?.models ?: return emptyList()
        return (list as List<Item>).filter { it.checked }.map { it.id }
    }

    /**
     * 获取开始时间
     */
    fun getStartDate(): Date? = when {
        startTime != null && startTime.textString().isNotEmpty() -> {
            startTime.textString().toDate(format = "yyyy-MM-dd")
        }
        mileageCountModel -> initStartDate
        else -> null
    }

    /**
     * 获取结束时间
     */
    fun getEndDate(): Date? = when {
        endTime != null && endTime.textString().isNotEmpty() -> {
            endTime.textString().toDate(format = "yyyy-MM-dd")
        }
        mileageCountModel -> initEndDate
        else -> null
    }

    override fun getMaxHeight(): Int {
        return ((screenHeight() - dp2px(125)) * 0.8).toInt()
    }

    private fun changeTabStatus(selectedPosition: Int){
        tabLayouts.forEachIndexed { index, layout ->
            layout.setBackgroundColor(if (index == selectedPosition) Color.WHITE else R.color.color_F3F3F3.toColorRes())
            tabBars[index].visible(index == selectedPosition)
            tabTexts[index].setTextColor(if (index == selectedPosition) R.color.theme.toColorRes() else R.color.color_666666.toColorRes())
        }
    }

    /**
     * 设置确认点击事件
     */
    fun setOnConfirmListener(listener: CommonCallback){
        this.onConfirmListener = listener
    }

    /**
     * 设置企业树数据
     */
    fun setCompanyTreeData(data: List<Tree>?){
        this.companyTreeData = data
        companyListView?.models = data
    }

    /**
     * 设置监管类型数据
     */
    fun setManageTypeData(data: List<Item>){
        this.manageTypeData = data
        typeListView?.models = data
    }

    /**
     * 递归更新复选框状态
     */
    private fun updateCheckBoxState(menu: Tree, checked: Boolean){
        menu.checked = checked
        menu.getItemSublist()?.forEach {
            val item = (it as Tree)
            item.checked = checked
            updateCheckBoxState(item, checked)
        }
    }

    /**
     * 递归提取所有节点及其子孙节点的id
     */
    private fun extractChildMenuId(selectedMenus: List<Tree>?, resultList: HashSet<String>) {
        if (selectedMenus.isNullOrEmpty()) return
        selectedMenus.forEach {
            resultList.add(it.id)
            if (!it.getItemSublist().isNullOrEmpty()){
                extractChildMenuId(it.getItemSublist() as List<Tree>, resultList)
            }
        }
    }

}